package com.daodaoclub.payment.common;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CollectionHelper {
	
	public static <K, V> String map2String(Map<K, V> map){
		if(map == null) return null;
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			String json = mapper.writeValueAsString(map);
			return json;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <K, V> Map<K, V> string2Map(String json){
		if(json == null || "".equals(json.replace(" ", ""))) return null;
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			Map<K, V> map = mapper.readValue(json, HashMap.class);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static  String sortColumn(SortedMap<String, String> sortedParamMap) {
		if (sortedParamMap.isEmpty()) {
			return "";
		}
		StringBuffer buffer = new StringBuffer();
		Iterator<Map.Entry<String, String>> iter = sortedParamMap.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> kvpair = iter.next();
			buffer.append(kvpair.getKey());
			buffer.append("=");
			if(kvpair.getValue() == null || "".equals(kvpair.getValue().replace(" ", ""))){
				buffer.append(kvpair.getValue());
			}
			if (iter.hasNext()) {
				buffer.append("&");
			}
		}
		String canonical = buffer.toString();
		return canonical;
	}
	
	public static void main(String[] args) {
		
	}
}

